package com.quartz.tasks.web.service;

import com.quartz.tasks.web.entity.HttpResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @author 彭长云
 * @Description:RestTempLate请求类
 * @date 2018/12/5 19:46
 */
@Component
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @Description:json请求
     */
    public HttpResultEntity post(String url,String requestJson) throws Exception{
        ResponseEntity<String> entity = null;
        String exception = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
            entity = restTemplate.postForEntity(url, request, String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            exception = e.getMessage();
        }
        return httpResultEntity(entity,exception);
    }

    /**
     *
     *@author： 彭长云
     * @Description:返回请求结果
     * @date： 2018/12/6 11:20
     */
    private HttpResultEntity httpResultEntity(ResponseEntity<String> responseEntity,String exception){
        HttpResultEntity httpResultEntity = new HttpResultEntity();
        if(responseEntity != null){
            httpResultEntity.setStatusCode(responseEntity.getStatusCode().toString());
            httpResultEntity.setBody(responseEntity.getBody());
        }
        httpResultEntity.setException(exception);
        return httpResultEntity;
    }
}
